package org.hackystat.iw.projectoverviewer.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * This class handles the import and export of the XML files for the jaxb generated classes.
 * 
 * @author Jianfei Liao
 */
public class XmlConverter {
  
  /**
   * Converts the specified XML file to the appropriate object.
   * 
   * @param file The source XML file.
   * @param packageName The name of the package used.
   * @return The unmarshalled object, which is of type based on the XML file.
   */
  public static Object xmlToObject(File file, String packageName) {
    try {
      JAXBContext jaxbContext = JAXBContext
          .newInstance(packageName);
      File sourceFile = file;
      // unmarshall the source file
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      // return the appropriate object depends on the XML file
      return unmarshaller.unmarshal(sourceFile);
    }
    catch (JAXBException e) {
      e.printStackTrace();
    }
    // return null if there is error
    return null;
  }
  
  /**
   * Converts the object to the appropriate XML file.
   * 
   * @param source The source object.
   * @param file The destination file.
   * @param packageName The name of the package used.
   * @return true if the conversion is successful, false otherwise.
   */
  public static boolean objectToXml(Object source, File file, String packageName) {
    boolean isExported = false;
    try {
      File xmlFile = file;
      Object sourceObject = source;
      
      JAXBContext jaxbContext = JAXBContext
          .newInstance(packageName);
      Marshaller marshaller = jaxbContext.createMarshaller();
      // set the marshaller to do formatted output to the XML file
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      OutputStream os = new FileOutputStream(xmlFile);
      // writes to the xml file
      marshaller.marshal(sourceObject, os);
      os.close();
      isExported = true;
    }
    catch (Exception e) {
      System.out.println("*** Error during conversion ***"); 
      e.printStackTrace();
    }
    return isExported;
  }
  
}
